package com.greate.community.config;

import com.greate.community.auth.wechatauth.wechat.WeChatAuthorizationConfig;
import com.greate.community.auth.wechatauth.wechat.WeChatOAuth2ClientContextFilter;
import com.greate.community.filter.AuthenticationTokenFilter;
import com.greate.community.constant.CommunityConstant;
import com.greate.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    private final WeChatAuthorizationConfig weChatAuthorizationConfig;
    private final WeChatOAuth2ClientContextFilter weChatOAuth2ClientContextFilter;
    private final AuthenticationTokenFilter authenticationTokenFilter;

    public SecurityConfig(WeChatAuthorizationConfig weChatAuthorizationConfig,
                          WeChatOAuth2ClientContextFilter weChatOAuth2ClientContextFilter,
                          AuthenticationTokenFilter authenticationTokenFilter) {
        this.weChatAuthorizationConfig = weChatAuthorizationConfig;
        this.weChatOAuth2ClientContextFilter = weChatOAuth2ClientContextFilter;
        this.authenticationTokenFilter = authenticationTokenFilter;
    }

    /**
     * 静态资源
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    // 认证环节我们使用自己的代码 LoginController，绕过 Spring Security 的

    /**
     * 授权
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //启用无状态session
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers(
                        "/user/get",
                        "/user/realname/get",
                        "/user/username",
                        "/user/password",
                        "/user/realname/update",
                        "/user/updateHeader",
                        "/letter/**",
                        "/notice/**",
                        "/exp/**",
                        "/cos/credential",
                        "/message/unread",
                        "/message/allread",
                        "/logout"
                )
                .hasAnyAuthority(
                        AUTHORITY_USER,
                        AUTHORITY_HUSTER,
                        AUTHORITY_MANAGER,
                        AUTHORITY_ADMIN
                )
                .antMatchers(
                        "/like",
                        "/follow",
                        "/unfollow",
                        "/discuss/delete/**",
                        "/discuss/add",
                        "/comment/add",
                        "/comment/delete/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_HUSTER,
                        AUTHORITY_MANAGER,
                        AUTHORITY_ADMIN
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/disable/**",
                        "/comment/disable/**",
                        "/data/**",
                        "/cos/admin/credential",
                        "/admin/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_MANAGER,
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll();

        //添加jwt认证器
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加微信登录认证器
        http.addFilterBefore(weChatAuthorizationConfig.weChatFilter(), BasicAuthenticationFilter.class);
        http.addFilterBefore(weChatOAuth2ClientContextFilter, OAuth2ClientAuthenticationProcessingFilter.class);

        // 权限不够时的处理
        http.exceptionHandling()
                // 1. 未登录时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        // 异步请求
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/plain;charset=utf-8");
                        response.getWriter().write(CommunityUtil.getJSONString(403, "你还没有登录"));
                    }
                })
                // 2. 权限不够时的处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        // 异步请求
                        response.setContentType("application/plain;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        writer.write(CommunityUtil.getJSONString(403, "你没有访问该功能的权限"));
                    }
                });

        // Security 底层会默认拦截 /logout 请求，进行退出处理
        // 此处赋予它一个根本不存在的退出路径，使得程序能够执行到我们自己编写的退出代码
        http.logout().logoutUrl("/securitylogout");

        http.headers().frameOptions().sameOrigin();
    }
}




